package com.ruoyi.shop.controller;

import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.shop.domain.CheShop;
import com.ruoyi.shop.service.ICheShopService;
import com.ruoyi.shop.util.SmsUtil;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ShopLonginController
 * @Description TODO
 * @Author xgj
 * @Date 2025年01月07日 下午2:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/login")
public class ShopLonginController {
    @Autowired
    private ICheShopService cheShopService;
    @Autowired
    private RedisTemplate redisTemplate;



    @Autowired
    private RemoteUserService remoteUserService;


    public static String generateToken(String phone, String code) {
        // 将phone和code组合成一个字符串
        String input = phone + code;

        // 计算SHA-1哈希值
        String hash = sha1Hash(input);

        // 返回哈希值的前n个字符作为最终的token（如果需要更短的token）
        // 这里我们返回整个哈希值，但你可以根据需要截取部分
        return hash;
    }
    //  sha-1算法生成
    private static String sha1Hash(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            StringBuilder hexString = new StringBuilder();

            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 algorithm not found", e);
        }
    }

    @PostMapping("/validate")
    public AjaxResult vd(@RequestBody Map<String, String> payload){
        String phone = payload.get("phone");
        String code = payload.get("code");

        R<LoginUser> userInfo = new R<LoginUser>();
        CheShop byPhone = new CheShop();
        String token = null;
        System.out.println(phone);


        if(phone!=null&&!"".equals(phone)){
            Object cd = redisTemplate.opsForValue().get(phone);
            System.out.println(cd.toString());
            if(cd != null && cd.equals(code)){
                //  验证成功，查询数据库，执行登录操作
//                AjaxResult byPhone = remoteShopService.findByPhone(phone, SecurityConstants.INNER);
                byPhone = cheShopService.selectCheShopByPhone(phone);
                System.out.println(byPhone);
                userInfo = remoteUserService.getUserInfo(byPhone.getName(), SecurityConstants.INNER);
                if(byPhone!=null){
                    //  生成token存入Redis
                    token = generateToken(phone, code);
                    redisTemplate.opsForValue().set(CacheConstants.LOGIN_TOKEN_KEY + token, phone+":"+code+":"+token, 1500, TimeUnit.MINUTES);
                }else{
                    return AjaxResult.error("不存在该用户，请先进行注册！");
                }

            }else {
                return AjaxResult.error("手机号或验证码不正确 ");
            }
        }else{
            return AjaxResult.error("手机号为空 ");
        }
        return AjaxResult.success(byPhone);
    }




    @PostMapping("/send/{phoneNumber}")
    public ResponseEntity<String> Send(@PathVariable(value = "phoneNumber") String phoneNumber){
        try {
            // 创建一个Random实例
            Random random = new Random();

            String code = "";

            // 循环四次以生成四个随机数字
            for (int i = 0; i < 4; i++) {
                // 生成一个0到9之间的随机整数，并将其转换为字符后追加到code中
                int randomNumber = random.nextInt(10); // nextInt(10)会生成一个0（包含）到10（不包含）之间的整数
                code+=randomNumber;
            }
            SmsUtil.send(phoneNumber,code);
            // 将验证码存储到Redis中，使用电话号码作为键
            redisTemplate.opsForValue().set(phoneNumber, code, 10, TimeUnit.MINUTES);

            // 返回响应
            return ResponseEntity.ok("SMS send request received for phone number: " + phoneNumber);
        } catch (Exception e) {
            // 处理异常，例如记录日志或返回错误响应
            return ResponseEntity.status(500).body("Failed to send SMS: " + e.getMessage());
        }
    }
}
